package com.portal.backend.service.impl;

import com.portal.backend.exception.ResourceNotFoundException;
import com.portal.backend.exception.UnauthorizedException;
import com.portal.backend.model.Article;
import com.portal.backend.model.Comment;
import com.portal.backend.model.User;
import com.portal.backend.payload.CommentRequest;
import com.portal.backend.payload.CommentResponse;
import com.portal.backend.payload.UserSummary;
import com.portal.backend.security.UserPrincipal;
import com.portal.backend.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.portal.backend.mapper.CommentMapper;
import com.portal.backend.mapper.ArticleMapper;
import com.portal.backend.mapper.UserMapper;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public CommentResponse createComment(Long articleId, CommentRequest commentRequest) {
        UserPrincipal userPrincipal = (UserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User author = userMapper.selectById(userPrincipal.getId());
        Article article = articleMapper.selectById(articleId);
        if (author == null) {
            throw new ResourceNotFoundException("User", "id", userPrincipal.getId());
        }
        if (article == null) {
            throw new ResourceNotFoundException("Article", "id", articleId);
        }
        Comment comment = new Comment();
        comment.setContent(commentRequest.getContent());
        comment.setArticleId(articleId);
        comment.setUserId(author.getId());
        commentMapper.insert(comment);
        return mapCommentToResponse(comment);
    }

    @Override
    public IPage<CommentResponse> getCommentsByArticleId(Long articleId, long current, long size) {
        Article article = articleMapper.selectById(articleId);
        if (article == null) {
            throw new ResourceNotFoundException("Article", "id", articleId);
        }
        Page<Comment> page = commentMapper.selectPage(
            new Page<>(current, size),
            new QueryWrapper<Comment>().eq("article_id", articleId).orderByDesc("created_at")
        );
        return page.convert(this::mapCommentToResponse);
    }

    @Override
    public CommentResponse getCommentById(Long commentId) {
        Comment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            throw new ResourceNotFoundException("Comment", "id", commentId);
        }
        return mapCommentToResponse(comment);
    }

    @Override
    public CommentResponse updateComment(Long commentId, CommentRequest commentRequest) {
        Comment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            throw new ResourceNotFoundException("Comment", "id", commentId);
        }
        UserPrincipal userPrincipal = (UserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (!comment.getUserId().equals(userPrincipal.getId())) {
            throw new UnauthorizedException("You are not authorized to update this comment.");
        }
        comment.setContent(commentRequest.getContent());
        commentMapper.updateById(comment);
        return mapCommentToResponse(comment);
    }

    @Override
    public void deleteComment(Long commentId) {
        Comment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            throw new ResourceNotFoundException("Comment", "id", commentId);
        }
        UserPrincipal userPrincipal = (UserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        boolean isCommentAuthor = comment.getUserId().equals(userPrincipal.getId());
        Article article = articleMapper.selectById(comment.getArticleId());
        boolean isArticleAuthor = article != null && article.getUserId().equals(userPrincipal.getId());
        if (!isCommentAuthor && !isArticleAuthor) {
            throw new UnauthorizedException("You are not authorized to delete this comment.");
        }
        commentMapper.deleteById(commentId);
    }

    private CommentResponse mapCommentToResponse(Comment comment) {
        CommentResponse response = new CommentResponse();
        response.setId(comment.getId());
        response.setContent(comment.getContent());
        User author = userMapper.selectById(comment.getUserId());
        response.setAuthor(new UserSummary(author.getId(), author.getUsername(), author.getFullName(), author.getAvatar()));
        response.setArticleId(comment.getArticleId());
        response.setCreatedAt(comment.getCreatedAt());
        response.setUpdatedAt(comment.getUpdatedAt());
        return response;
    }
} 